package com.jinshan.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinshan.edu.entity.EduSection;
import com.jinshan.edu.mapper.EduSectionMapper;
import com.jinshan.edu.service.EduSectionService;
import com.jinshan.edu.service.VideoServiceFeign;
import com.jinshan.exception.EduException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程小节 服务实现类
 * </p>
 *
 * @author Jinshan
 * @since 2020-06-27
 */
@Service
public class EduSectionServiceImpl extends ServiceImpl<EduSectionMapper, EduSection> implements EduSectionService {
    @Autowired
    private VideoServiceFeign videoServiceFeign;

    @Override
    public void saveSection(EduSection eduSection) {
        baseMapper.insert(eduSection);
    }

    @Override
    public boolean deleteSectionById(String id) {
        EduSection section = baseMapper.selectById(id);
        String videoSourceId = section.getVideoSourceId();
        if (StringUtils.isNotEmpty(videoSourceId)) {
            // TODO 通过远程RPC调用删除视频
            try {
                videoServiceFeign.deleteVideoFromAliyun(videoSourceId);
            } catch (Exception e) {
                e.printStackTrace();
                throw new EduException(20004, "删除单个section时删除视频失败");
            }
        }
        int rows = baseMapper.deleteById(id);
        return rows > 0;
    }

    @Override
    public void updateSection(EduSection section) {
        baseMapper.updateById(section);
    }

    @Override
    public EduSection getSectionById(String id) {
        EduSection section = baseMapper.selectById(id);
        return section;
    }

    @Override
    public void deleteSectionByCourseId(String courseId) {
        QueryWrapper<EduSection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        List<EduSection> selectList = baseMapper.selectList(queryWrapper);
        List<String> videoSourceIds = new ArrayList<>();
        for (EduSection section : selectList) {
            String videoSourceId = section.getVideoSourceId();
            if (StringUtils.isNotEmpty(videoSourceId)) {
                videoSourceIds.add(videoSourceId);
            }
        }

        // TODO 远程调用video服务, 删除视频
        try {
            videoServiceFeign.deleteMultipleVideosFromAliyun(videoSourceIds);
        } catch (Exception e) {
            e.printStackTrace();
            throw new EduException(20003, "删除课程时批量删除视频失败");
        }
        // 删除所有的section
        baseMapper.delete(queryWrapper);
    }
}
